from django.views.generic import View
from django.http import JsonResponse
from django.shortcuts import render

from apps.operations.forms import UserFavForm, CommentsForm
from apps.operations.models import UserFavorite, CourseComments, Banner
from apps.courses.models import Course
from apps.organizations.models import CourseOrg, Teacher


class IndexView(View):
    """首页"""
    def get(self, request, *args, **kwargs):
        # # 500 错误
        # 1/0
        # # 403 权限错误
        # from django.core.exceptions import PermissionDenied
        # raise PermissionDenied
        banners = Banner.objects.all().order_by("index")
        courses = Course.objects.filter(is_banner=False)[:6]
        banner_courses = Course.objects.filter(is_banner=True)
        course_org = CourseOrg.objects.all()[:15]
        return render(request, "index.html", {
            "banners": banners,
            "courses": courses,
            "banner_courses": banner_courses,
            "course_org": course_org
        })


class CommentView(View):
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            # 先判断用户是否登录
            return JsonResponse({
                "status": "fail",
                "msg": "用户未登录"
            })
        comment_form = CommentsForm(request.POST)
        if comment_form.is_valid():
            # 传统校验
            # course_id = comment_form.cleaned_data["course"]
            # 利用model.Forms 校验，传入外键的id 返回外键的对象
            course = comment_form.cleaned_data["course"]
            # 通过forms.ModelForm表单外键 筛选的数据对象
            comments = comment_form.cleaned_data["comments"]

            comment = CourseComments()
            comment.user = request.user
            comment.comments = comments
            # 传统校验
            # course = Course.objects.get(id=course_id)
            comment.course = course
            comment.save()

            return JsonResponse({
                "status": "success"
            })

        return JsonResponse({
            "status": "fail",
            "msg": "参数错误"
        })


class AddFavView(View):
    def post(self, request, *args, **kwargs):
        """用户收藏，取消收藏"""
        if not request.user.is_authenticated:
            # 先判断用户是否登录
            return JsonResponse({
                "status": "fail",
                "msg": "用户未登录"
            })
        user_fav_form = UserFavForm(request.POST)
        # 如果用户未登录不能收藏
        if user_fav_form.is_valid():
            fav_id = user_fav_form.cleaned_data["fav_id"]
            fav_type = user_fav_form.cleaned_data["fav_type"]

            # 是否已经收藏
            existed_records = UserFavorite.objects.filter(user=request.user, fav_id=fav_id, fav_type=fav_type)
            if existed_records:
                # 已经收藏
                existed_records.delete()

                if fav_type == 1:
                    # 判断收藏的类型(课程)
                    course = Course.objects.get(id=fav_id)
                    course.fav_nums -= 1
                    course.save()
                elif fav_type == 2:
                    # 课程机构
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.fav_nums -= 1
                    course_org.save()
                elif fav_type == 3:
                    # 教师
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.fav_nums -= 1
                    teacher.save()

                return JsonResponse({
                    "status": "success",
                    "msg": "收藏"
                })

            else:
                # 未收藏，在UserFavorite的表中新增数据
                user_fav = UserFavorite()
                user_fav.fav_id = fav_id
                user_fav.fav_type = fav_type
                user_fav.user = request.user
                user_fav.save()
                if fav_type == 1:
                    # 判断收藏的类型(课程)
                    course = Course.objects.get(id=fav_id)
                    course.fav_nums += 1
                    course.save()
                elif fav_type == 2:
                    # 课程机构
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.fav_nums += 1
                    course_org.save()
                elif fav_type == 3:
                    # 教师
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.fav_nums += 1
                    teacher.save()

                return JsonResponse({
                    "status": "success",
                    "msg": "已收藏"
                })

        else:
            return JsonResponse({
                "status": "fail",
                "msg": "参数错误"
            })


